<template>
  <div>
    <div class="seal-cost-content">
      <div class="mt12 mb12 filter-form">
        <FilterInput v-if="!showMobilePage" ref="FilterToolRef" v-model="paramsObj" :is-show-filter="isShowFilter" :filter-list="filterList" show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" />
        <div v-if="!showMobilePage" class="export-wrap flex-center">
          <topRightAmount :total-tax-amount="list.otherData && list.otherData.totalTaxAmount" title="含税成本" />
          <export-button
            ref="costExportRef"
            :export-api="'/admin/review/costList/export'"
            :export-name="'封账成本'"
            is-before-export
            class="btn-right-item"
            is-diy
            style="padding: 0"
            @beforeExport="exportBeforeExport('costExportRef')"
            @onComplate="exportComplete">
            <el-button
              :disabled="exportLoading"
              :loading="exportLoading"
              class="export-btn"
              size="small"
              type="primary"
              plain>导出</el-button>
          </export-button>
        </div>
        <div v-else class="export-wrap flex-center mobile-export-wrap">
          <topRightAmount :total-tax-amount="list.otherData && list.otherData.totalTaxAmount" title="含税成本" />
          <div class="btn-wrap">
            <FilterInput ref="FilterToolRef" v-model="paramsObj" :is-show-filter="isShowFilter" :filter-list="filterList" :show-text="false" show-mobile-icon show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" />
            <export-button
              ref="costExportRef"
              :export-api="'/admin/review/costList/export'"
              :export-name="'封账成本'"
              is-before-export
              class="btn-right-item"
              is-diy
              style="padding: 0"
              @beforeExport="exportBeforeExport('costExportRef')"
              @onComplate="exportComplete">
              <img :src="exportImg" class="export-icon" alt="export" >
            </export-button>
          </div>
        </div>
      </div>
      <div class="table-wrap">
        <el-table
          v-loading="listLoading"
          ref="costTableRef"
          :data="list.items"
          :header-cell-style="{fontSize: '14px',color: '#141C3D'}"
          :row-class-name="(data) => tableRowClassName(data)"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          fit
          hightlight-current-row
          class="fb-table"
          header-cell-class-name="order-data-header-cell"
          @sort-change="sortMethod"
          @select="selectTable"
          @select-all="selectTable"
          @selection-change="handleSelectionChange">
          <el-table-column
            v-if="!isReport"
            align="left"
            type="selection"
            width="55"
            fixed="left"
          />
          <el-table-column align="left" label="成本编号" min-width="200">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.costNum" class="item" placement="top" effect="dark">
                <div slot="content" class="max-width-200">{{ scope.row.costNum }}</div>
                <div class="project-num ellipsis" @click="toCostDetail(scope.row)">{{ scope.row.costNum }}</div>
              </el-tooltip>
              <div v-else class="project-num" @click="toCostDetail(scope.row)">--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="下单日期" width="110" prop="orderDate">
            <template slot-scope="scope">
              <div v-if="scope.row.orderDate">{{ scope.row.orderDate | standardFormat('YYYY/MM/DD') }}</div>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="成本项" width="100">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.costItemName" class="item" placement="top" effect="dark">
                <div slot="content" class="max-width-200">{{ scope.row.costItemName }}</div>
                <div class="ellipsis">{{ scope.row.costItemName }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="right" label="含税成本(元)" min-width="140" prop="taxCost" sortable="custom">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.taxCost" :price="scope.row.taxCost / 100" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="供应商" width="220">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.supplierName" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="审批状态" width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.approvalStatus || scope.row.approvalStatus === APPROVAL_STATUS.PENDING" class="dot-wrap">
                <span :style="{backgroundColor: getColor(scope.row.approvalStatus)}" class="dot"/>
                {{ scope.row.approvalStatus | costApprovalStatus }}
              </div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="成本状态" width="80">
            <template slot-scope="scope">
              <div v-if="scope.row.settlementStatus || scope.row.settlementStatus === SETTLEMENT_STATUS.TO_BE_SETTLED" class="dot-wrap">
                <span :style="{backgroundColor: getCostColor(scope.row.settlementStatus)}" class="dot"/>
                {{ scope.row.settlementStatus | settlementStatusFilter }}
              </div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="说明" width="160">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.costDescription" class="item" placement="top" effect="dark">
                <div slot="content" class="max-width-200">{{ scope.row.costDescription }}</div>
                <div class="ellipsis">{{ scope.row.costDescription }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="可抵扣税率" min-width="100" prop="discount">
            <template slot-scope="scope">
              <div v-if="scope.row.discount || scope.row.discount === 0">
                {{ scope.row.discount }} %
              </div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="关联订单" width="190" prop="isNotRelateOrder" sortable="custom">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.isNotRelateOrder" class="item" placement="top" effect="dark">
                <div slot="content" class="max-width-200">{{ scope.row.relatedOrderNum || '--' }}</div>
                <div class="ellipsisOne" style="cursor:pointer;color: #406EFF;" @click="goDetail(scope.row)">{{ scope.row.relatedOrderNum }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="成本来源" width="90">
            <template slot-scope="scope">
              {{ scope.row.costBelong | costBelongFilter }}
            </template>
          </el-table-column>
          <el-table-column align="left" label="成本类型" width="120">
            <template slot-scope="scope">
              {{ scope.row.costType | costTypeFilter }}
            </template>
          </el-table-column>
          <el-table-column align="left" label="所属部门" width="100">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.departmentName" class="item" effect="dark" placement="top-start">
                <div slot="content" style="max-width: 200px;">{{ scope.row.departmentName }}</div>
                <div class="ellipsisOne">{{ scope.row.departmentName }}</div>
              </el-tooltip>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="审批时间" width="160" prop="approvalDate">
            <template slot-scope="scope">
              <div v-if="scope.row.approvalDate">{{ scope.row.approvalDate | standardFormat('YYYY/MM/DD HH:mm:ss') }}</div>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="创建时间" width="160" prop="createDate" sortable="custom">
            <template slot-scope="scope">
              <div v-if="scope.row.createDate">{{ scope.row.createDate | standardFormat('YYYY/MM/DD HH:mm:ss') }}</div>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="创建人" width="90">
            <template slot-scope="scope">
              {{ scope.row.creator || '--' }}
            </template>
          </el-table-column>
          <el-table-column :width="showMobilePage ? 50 : (hasRouteAuth('crm:finance:financeRecheck') && isRecheck ? 220 : 100)" align="center" label="操作" fixed="right">
            <template slot-scope="scope">
              <template v-if="!showMobilePage">
                <div class="row-cell">
                  <reviewColumn
                    :is-recheck="isRecheck"
                    :is-report="isReport"
                    :item="scope.row"
                    :sealing-id="sealingId"
                    :column-type="'cost'"
                    @freshData="getData" />
                  <el-button
                    v-if="!isReport && !isRecheck"
                    :disabled="!canEdit(scope.row.approvalStatus)"
                    type="text"
                    size="small"
                    class="m0 p0"
                    @click.native="openDialog('edit', scope.row.id)"
                  >
                    <div class="editCost">
                      <span style="color: #406EFF;margin: 1px 5px 0;transform: scaleY(0.8);">|</span>
                      <span>编辑</span>
                    </div>
                  </el-button>
                </div>
              </template>
              <reviewColumn
                v-else
                :is-recheck="isRecheck"
                :is-report="isReport"
                :has-edit="!isReport && !isRecheck"
                :edit-disabled="!canEdit(scope.row.approvalStatus)"
                :item="scope.row"
                :sealing-id="sealingId"
                :column-type="'cost'"
                @costEdit="openDialog('edit', scope.row.id)"
                @freshData="getData" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <fixed-pagination v-show="list.total > 0" :class="{'position-b56': !showMobilePage, 'position-b49': showMobilePage}" class="center">
        <div style="flex:1;display:flex;">
          <tableFooterBtn
            v-if="!isReport"
            ref="tableFooterBtn"
            :select-data="multipleSelection"
            :process-state="processState"
            :sealing-id="sealingId"
            :multiple-selection-all="multipleSelectionAll"
            column-type="cost"
            @clearMixinSelection="clearMixinSelection"
            @queryClick="queryClick"
            @refreshData="refreshData" />
        </div>
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="showMobilePage ? pageLayout : 'total, prev, pager, next, sizes'"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </fixed-pagination>
    </div>
    <CreateEditCost
      ref="createEditCost"
      :cost-id="costId"
      :type="opreateType"
      :is-from-sealing="true"
      @submit="queryEmpty"
      @handleClose="handleClose"/>

  </div>
</template>
<script>
import orderEdit from '@/assets/order-edit.png';
import defaultEdit from '@/assets/defalut-edit.png';

// api
import { getDepartment } from '@/api/project';
import { costList } from '@/api/config';
import { getSealCostList } from '@/api/sealingAccount';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { approvalStatus, settlementStatus } from '@/views/cost/model/selectData';
import reviewColumn from '../reviewColumn';
import tableFooterBtn from '../tableFooterBtn';
import topRightAmount from '../topRightAmount';
// filter
import {
  settlementStatusFilter,
  costBelongFilter,
  costTypeFilter,
  costApprovalStatus,
  setSealBillType } from '@/filters/status';
import { moneyFilter } from '@/filters/number';
import { standardFormat } from '@/filters/date';
import { hasRouteAuth } from '@/utils/permission';
import { paramsFormat, paramsRangeFormat } from '@/utils/paramsFormat';
import isAdmin from '@/mixins/isAdmin';
import costSet from '@/mixins/costSet';
import paramsDateFormat from '@/mixins/paramsDateFormat';
import { HANDLE_ACTIVE, APPROVAL_STATUS, SETTLEMENT_STATUS, BELONG } from '@/utils/const/cost';
import SealingMixins from '@/components/Finance/mixins/sealing';
import tableSelections from '@/mixins/tableSelections';
import ExportButton from '@/components/ExportButton';
import exportImg from '@/assets/export.png';
import mobileTable from '@/mixins/mobileTable';

import { PROCESS_STATE } from '@/utils/const/sealing';
export default {
  components: {
    EmptyPlaceholder,
    reviewColumn,
    topRightAmount,
    tableFooterBtn,
    ExportButton,
    CreateEditCost: () => import('@/components/Cost/createCost')
  },
  filters: {
    moneyFilter,
    settlementStatusFilter,
    costBelongFilter,
    costTypeFilter,
    standardFormat,
    costApprovalStatus,
    setSealBillType },
  mixins: [
    isAdmin,
    costSet,
    mobileTable,
    paramsDateFormat,
    tableSelections,
    SealingMixins],
  props: {
    // true：复审，false：初审
    isRecheck: {
      type: Boolean,
      default: false
    },
    // true: 初审/复审，false：查看报告
    isReport: {
      type: Boolean,
      default: true
    },
    sealingId: {
      type: Number,
      default: null
    },
    processState: {
      type: Number | String,
      default: PROCESS_STATE.REVIEW
    }
  },
  data() {
    return {
      orderEdit, defaultEdit,
      exportImg,
      listLoading: false,
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInint: true
      },
      paramsObj: {},
      departmentOption: [],
      costItem: [],
      isShowFilter: false,
      opreateType: '',
      costId: 0,
      tableRefName: 'costTableRef',
      dateDataAttrName: [
        {
          attr: 'createTime',
          start: 'createDateStart',
          end: 'createDateEnd',
          endType: 1
        },
        {
          attr: 'approvalTime',
          start: 'approvalDateStart',
          end: 'approvalDateEnd',
          endType: 1
        },
        {
          attr: 'orderDate',
          start: 'orderDateStart',
          end: 'orderDateEnd',
          endType: 1
        }
      ],
      HANDLE_ACTIVE,
      APPROVAL_STATUS,
      SETTLEMENT_STATUS,
      multipleSelection: []
    };
  },
  computed: {
    filterList() {
      return [
        // 输入框
        { keyword: 'costNum', name: '成本编号', labelWidth: '70px', type: 'input' },
        { keyword: 'supplierName', name: '供应商', labelWidth: '70px', type: 'input' },
        { keyword: 'relatedOrderNum', name: '关联订单', labelWidth: '70px', type: 'input' },
        { keyword: 'creator', name: '创建人', labelWidth: '70px', type: 'input' },
        { keyword: 'taxCost', name: '含税成本', labelWidth: '70px', type: 'inputRange' },
        // 下拉
        { keyword: 'departmentId', name: '所属部门', type: 'select', isSearch: true, options: this.departmentOption }, // 可搜索下拉
        { keyword: 'costItemName', name: '成本项', type: 'select', options: this.costItem },
        { keyword: 'costBelong', name: '成本来源', type: 'select', options: [
          { value: 0, label: '渠道订单' }, { value: 1, label: '项目订单' }, { value: 2, label: '商务订单' },
          { value: 3, label: '营销授权' }, { value: 5, label: '项目渠道单' }] },
        { keyword: 'settlementStatus', name: '成本状态', type: 'select', options: settlementStatus },
        { keyword: 'approvalStatus', name: '审批状态', type: 'select', options: approvalStatus },
        // 日期
        { keyword: 'orderDate', name: '下单日期', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'createTime', name: '创建时间', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'approvalTime', name: '审批时间', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' }
      ];
    }
  },
  created() {
    this.getDepartmentData();
    this.getCostItemList();
  },
  methods: {
    hasRouteAuth,
    canEdit(aStatus) {
      return aStatus === APPROVAL_STATUS.PENDING || aStatus === APPROVAL_STATUS.REFUSE;
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = 'createDate';
        this.sortType = -1;
      } else {
        // 2.8.4关联订单的sortName传order_id
        this.sortName = a.prop === 'isNotRelateOrder' ? 'order_id' : a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.getData();
    },
    // 获取成本管理下包含的部门
    getDepartmentData() {
      const params = {
        type: 6
      };
      getDepartment(params).then(res => {
        if (res.data) {
          res.data.unshift({ value: -2, label: '--' });
          this.departmentOption = res.data;
        }
      });
    },
    // 获取成本项列表
    getCostItemList() {
      costList({ getAll: 1 }).then(res => {
        if (res.data) {
          const costItem = res.data.items;
          const costItemList = [];
          costItem.forEach(item => {
            if (!costItemList.find(cost => cost.label === item.costName)) {
              const obj = {
                value: item.costId,
                label: item.costName
              };
              costItemList.push(obj);
            }
          });
          this.costItem = costItemList;
        }
      });
    },
    // 多选
    tableSelectionChange(e) {
      this.ids = e.map(item => item.id).join(',');
    },
    formatParams(sendPageConfig = true) {
      const { sortName, sortType, paramsObj, dateDataAttrName, page, perPage,
        processState, sealingId } = this;
      let params = JSON.parse(JSON.stringify(paramsObj));
      // 时间处理
      this.paramsDateFormat(dateDataAttrName, params, 's');
      params.sortName = 'createDate';
      params.sortType = -1;
      // 参数处理
      params = paramsFormat(params);
      if (sendPageConfig) {
        params.page = page;
        params.perPage = perPage;
      }
      if (sortName) {
        params.sortName = sortName;
        params.sortType = sortType;
      }
      /* if (params.taxCost && params.taxCost.length === 2) {
        params.taxCostStart = params.taxCost[0] || params.taxCost[0] === 0 ? Number(params.taxCost[0]) * 100 : null;
        params.taxCostEnd = params.taxCost[1] || params.taxCost[1] === 0 ? Number(params.taxCost[1]) * 100 : null;
        delete params.taxCost;
      } */
      paramsRangeFormat([{ attr: 'taxCost', start: 'taxCostStart', end: 'taxCostEnd', type: 'money' }], params);
      if (params.costItemName) {
        params.costItemName = this.costItem.find(item => item.value === params.costItemName).label;
      }
      params.processState = processState;
      params.id = sealingId;
      params.costBelong = params.costBelong || BELONG.CHANNEL;
      return params;
    },
    getData(reset = false) {
      if (reset) this.page = 1;
      const params = this.formatParams();
      if (this.isBatchAll) params.returnIds = true;
      this.listLoading = true;
      getSealCostList(params, this.sealingId).then((res = {}) => {
        const { data } = res;
        if (this.isBatchAll) {
          // 批量操作事件 先根据条件搜索出对应的id数组，再将id集合传送给操作接口
          this.operateHandle(this.requestType, res);
        } else {
          data.items.map(item => {
            if (item.department && item.department.length) item.departmentName = item.department.map(i => i.name).join(',');
            return item;
          });
          this.list = data;
          this.listLoading = false;
        }
        this.isBatchAll = false;
        this.setSelectRow && this.setSelectRow(res.data.items);
      }).catch(e => {
        this.isBatchAll = false;
        console.error(e);
      });
    },
    queryClick({ isBatchAll, type, listLoadingReset } = {}) {
      if (listLoadingReset) {
        this.listLoadingReset();
      } else {
        this.isBatchAll = isBatchAll;
        this.requestType = type;
        this.getData(!isBatchAll);
      }
    },
    toDetail(item) {
      this.$router.push({
        name: 'costDetail',
        params: { id: item.id }
      });
    },
    goDetail(item) {
      const id = item.relatedOrderId;
      let routeUrl = null;
      let params = {};
      if (item.costBelong === 0) {
        // 渠道订单
        params = {
          name: 'orderDetail',
          params: { orderId: id }
        };
      } else if (item.costBelong === 1) {
        // 项目订单
        params = {
          name: 'projectDetail',
          params: { id: id }
        };
      } else if (item.costBelong === 2) {
        // 商务订单
        params = { name: 'mengliOrderDetail', params: { id: id }, query: { type: 0 }};
      } else if (item.costBelong === 3) {
        // 营销授权
        params = { name: 'mengliOrderDetail', params: { id: id }, query: { type: 1 }};
      } else if (item.costBelong === 5) {
        // 项目渠道单
        params = { name: 'projectChildDetail', params: { id: id }};
      }
      routeUrl = this.$router.resolve(params);
      if (routeUrl) window.open(routeUrl.href, '_blank');
    },
    // 打开弹窗用于新增或修改 编辑，type: edit
    openDialog(type, id) {
      this.costId = id || 0;
      this.opreateType = type;
      this.$refs.createEditCost.openDialog();
      // this.$refs.createEditCost.formatSupplierName(supplierId, supplierName);
    },
    handleClose(value) {
      // 组件的关闭方法执行比$emit快 注意重置opreateType的时机要放在最后 用于编辑后跳转的页面应该是当前页
      setTimeout(() => {
        this.opreateType = value;
      }, 1000);
    },
    toCostDetail(item) {
      if (!item || !item.id) {
        this.$message.warning('无法获取id');
        return;
      }
      const url = this.$router.resolve({
        name: 'costDetail',
        params: { id: item.id }
      });
      window.open(url.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
@import '@/styles/placeholder.scss';
.dot-wrap {
  @extend %dot-wrap;
}
.project-num {
  color: #406EFF;
  cursor: pointer;
  span {
    cursor: pointer;
  }
}
.max-width-200 {
  max-width: 200px;
}
@import '@/styles/placeholder.scss';
.export-wrap {
  @extend %sealing-export-btn;
}
.editCost {
  display: flex;
  height: 16px;
  .icon-img {
    width: 14px;
    height: 14px;
  }
}
.el-table {
  &::v-deep {
    th .el-checkbox {
      margin: 0 4px;
    }
  }
}
.row-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  ::v-deep .sealing-check {
    .sealing-font {
      position: relative;
      top: 1px;
      left: 2px;
    }
  }
}
.mt12 {
  margin-top: 12px !important;
}
</style>
